package org.skydiveapplibrary.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class MD5Util
{
	public static String md5(byte[] bytes)
	{
		// Create MD5 Hash
		try
		{
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(bytes);
			byte messageDigest[] = digest.digest();

	        // Create Hex String
	        StringBuffer hexString = new StringBuffer();
	        for (int i=0; i<messageDigest.length; i++)
	            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
	        return hexString.toString();
		}
		catch (Exception ex)
		{
			return "";
		}
	}
	
	public static String md5(String filepath)
	{
		// Create MD5 Hash
		try
		{
			byte[] b = createChecksum(filepath);
		       String result = "";

		       for (int i=0; i < b.length; i++) {
		           result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
		       }
		       return result;
		}
		catch (Exception ex)
		{
			return("");
		}
	}
	
	public static byte[] createChecksum(String filename) throws Exception {
	       InputStream fis =  new FileInputStream(filename);

	       byte[] buffer = new byte[1024];
	       MessageDigest complete = MessageDigest.getInstance("MD5");
	       int numRead;

	       do {
	           numRead = fis.read(buffer);
	           if (numRead > 0) {
	               complete.update(buffer, 0, numRead);
	           }
	       } while (numRead != -1);

	       fis.close();
	       return complete.digest();
	 }
}
